package com.wjs.gulimall.gulimallproduct.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.wjs.gulimall.gulimallproduct.VO.*;
import com.wjs.gulimall.gulimallproduct.entity.*;
import com.wjs.gulimall.gulimallproduct.feign.CouponFeginService;
import com.wjs.gulimall.gulimallproduct.feign.SearchFeign;
import com.wjs.gulimall.gulimallproduct.feign.WareFeginService;
import com.wjs.gulimall.gulimallproduct.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.wjs.gulimall.gulimallproduct.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeginService couponFeginService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeginService wareFeginService;

    @Autowired
    private SearchFeign searchFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo saveVo) {
        //1 保存SPU基本信息 pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(saveVo, spuInfo);
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        this.save(spuInfo);

        //2 保存SPU的描述图片 pms_spu_info_desc
        List<String> decript = saveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfo.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoService.save(spuInfoDescEntity);

        //3 保存SPU的图片集pms_spu_images
        List<String> images = saveVo.getImages();
        spuImagesService.saveImages(spuInfo.getId(), images);

        //4 保存SPU的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = saveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((obj) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(obj.getAttrId());
            AttrEntity attr = attrService.getById(obj.getAttrId());
            productAttrValueEntity.setAttrName(attr.getAttrName());
            productAttrValueEntity.setSpuId(spuInfo.getId());
            productAttrValueEntity.setAttrValue(obj.getAttrValues());
            productAttrValueEntity.setQuickShow(obj.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrValue(collect);

        //保存SPU的积分信息
        Bounds bounds = saveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setSpuId(spuInfo.getId());
        spuBoundTo.setBuyBounds(bounds.getBuyBounds());
        spuBoundTo.setGrowBounds(bounds.getGrowBounds());
        couponFeginService.saveSpuBounds(spuBoundTo);

        //5 保存当前spu对应的所有sku信息
        // 5.1 sku的基本信息 pms_sku_info
        List<Skus> skus = saveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach((sku) -> {
                //拿到默认图片
                String defaultImage = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfo.getId());
                skuInfoEntity.setPrice(new BigDecimal(sku.getPrice()));
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoEntity.setSaleCount(0L);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                // 5.2 sku的图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesList = sku.getImages().stream().map((obj) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(obj.getDefaultImg());
                    skuImagesEntity.setImgUrl(obj.getImgUrl());
                    return skuImagesEntity;
                }).filter((obj) -> {
                    return !StringUtils.isEmpty(obj.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveSkuImages(skuImagesList);


                // 5.3 sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attr.stream().map((a) -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveSkuSaleAttrValue(saleAttrValueEntities);

                // 5.4 sku的优惠，满减信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                R r = couponFeginService.saveSkuReduction(skuReductionTo);
                if (r.getCode() != 0) {
                    log.error("远程服务调用失败");
                }
            });

        }

    }

    @Override
    public PageUtils querySpuinfo(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty((String) params.get("key"))) {
            wrapper.and((wq) -> {
                wq.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty((String) params.get("status"))) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty((String) params.get("brandId"))) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty((String) params.get("catelogId"))) {
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * spu上架
     *
     * @param spuId
     */
    @Override
    public void UpProduct(Long spuId) {
        // 1、查出当前 spuid 对应的所有skuid信息，品牌的名字
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSkuBySpuId(spuId);
        List<Long> SkuIds = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //调用远程服务
        Map<Long, Boolean> StockMap = null;
        try {
            R r = wareFeginService.getSkusHasstock(SkuIds);
            //拿到结果
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            List<SkuHasStockVo> StockList = (List<SkuHasStockVo>) r.getData(typeReference);
            //将结果封装成一个map
            StockMap = StockList.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常");
        }
        //查出sku所有可以被用来进行检索的信息
        List<ProductAttrValueEntity> attrs = productAttrValueService.listforspu(spuId);
        List<Long> attrIds = attrs.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        // 得到可查询的属性id
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> set = new HashSet<>(searchAttrIds);
        //封装获得es模型集合属性数据
        List<SkuEsModel.Attrs> attrsList = attrs.stream().filter((attr) -> {
            return set.contains(attr.getAttrId());
        }).map((attr) -> {
            SkuEsModel.Attrs sattr = new SkuEsModel.Attrs();
            sattr.setAttrId(attr.getAttrId());
            sattr.setAttrName(attr.getAttrName());
            sattr.setAttrValue(attr.getAttrValue());
            return sattr;
        }).collect(Collectors.toList());

        // 2 封装每个sku的信息
        Map<Long, Boolean> finalStockMap = StockMap;
        List<SkuEsModel> esModels = skuInfoEntityList.stream().map((sku) -> {
            SkuEsModel es = new SkuEsModel();
            BeanUtils.copyProperties(sku, es);
            es.setSkuPrice(sku.getPrice());
            es.setSkuImg(sku.getSkuDefaultImg());
            // 3 查询品牌和分类的信息
            BrandEntity brand = brandService.getById(es.getBrandId());
            es.setBrandName(brand.getName());
            es.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(es.getCatalogId());
            es.setCatalogName(category.getName());
            //设置检索属性
            es.setAttrs(attrsList);

            //设置热度评分
            es.setHotScore(0L);

            //设置是否有库存
            if (finalStockMap == null) {
                es.setHasStock(true);
            } else {
                es.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            return es;
        }).collect(Collectors.toList());

        //todo 发给es进行保存
        //远程调用es保存服务
        try {

            R r = searchFeign.SaveProduct(esModels);
            if (r.getCode() == 0) {
                //修改SPU上架状态
                spuInfoService.updateStatusById(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
            } else {
                //todo 重复调用的问题
            }
        } catch (Exception e) {

        }

    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        SpuInfoEntity entity = this.getById(byId.getSpuId());
        return entity;
    }

}